﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
using System.Xml.Serialization;
using Microsoft.Office.Interop.Excel;

namespace ObjectModel.Excel.Old
{
    /// <summary>
    /// Extends OfflineRange to include a collection of conditions
    /// that can be placed on the value resolution process.
    /// </summary>
    public class ConditionalOfflineRange : OfflineRange
    {
        public ObservableCollection<ValueCondition> Conditions { get; set; }

        public ConditionalOfflineRange()
        {
            Conditions = new ObservableCollection<ValueCondition>();
			Conditions.CollectionChanged += Conditions_CollectionChanged;
        }

        private void Conditions_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add)
                foreach (ValueCondition condition in e.NewItems)
                    condition.PropertyChanged += (o, ea) => { OnPropertyChanged("Value"); };

            OnPropertyChanged("Value");
        }

        public dynamic GetValue(bool transposed = false, int reqHeight = 0, int reqWidth = 0)
        {
            ApplyAllConditions();
        	Range result = Range; // Will get Range object from subclass if inherited.
           
			// Apply sized constraints
			if(reqHeight != 0) {
				result = result.Worksheet.Range[result.Worksheet.Cells[result.Row,result.Column],
								result.Worksheet.Cells[result.Row + reqHeight, result.Column + result.Columns.Count]];
			}

			if(reqWidth != 0) {
				result = result.Worksheet.Range[result.Worksheet.Cells[result.Row,result.Column],
								result.Worksheet.Cells[result.Row + result.Rows.Count, result.Column + reqWidth]];
			}

        	 return transposed ? result.TransposedValue() : result.Value;
        }

        private void ApplyAllConditions()
        {
            foreach (ValueCondition condition in Conditions)
                condition.Resolve();
        }
    }
}
